package com.phynos.web.manager.shiro;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Locale;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.util.StringUtils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.phynos.web.manager.json.JsonResult;
import com.phynos.web.manager.json.ResultCodeEnum;

/**
 * ajax请求过滤器（登录判断+多语言支持）
 * @author lupc
 *
 */
public class ShiroAjaxFilter extends AccessControlFilter {

	@Autowired
	private MessageSource messageSource;
	
	@Override
	protected boolean isAccessAllowed(ServletRequest arg0,
			ServletResponse arg1, Object arg2) throws Exception {
		return false;
	}

	@Override
	protected boolean onAccessDenied(
			ServletRequest request, 
			ServletResponse response)
			throws Exception {
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {// 表示没有登录，重定向到登录页面
        	HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
        	HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
			this.
        	redirectToLoginView(httpServletRequest,httpServletResponse);			
        } else {
        	 return true;
        }
        return false;
	}
	
	private Boolean redirectToLoginView(
			HttpServletRequest request,
			HttpServletResponse response){
		response.setContentType("text/html;charset=utf-8");
		response.setHeader("prama", "no-cache");
		response.setHeader("cache-control", "no-cache");
		OutputStreamWriter writer = null;
		ServletOutputStream os = null;
		try {  
			String lang = request.getParameter("lang"); 
			if(lang == null){
				lang = "zh_CN";
			}
			//获取格式化的国际化信息 			
			Locale locale = StringUtils.parseLocaleString(lang);
			String message = messageSource.getMessage(
					ResultCodeEnum.LOGIN_FIRST.getCode() + "",
					null,
					locale); 			
			os = response.getOutputStream();
			writer = new OutputStreamWriter(os, "UTF-8");
			JsonResult result = JsonResult.code(ResultCodeEnum.LOGIN_FIRST,message);
			ObjectMapper mapper = new ObjectMapper();
			String val = mapper.writeValueAsString(result);
			writer.write(val);
		} catch (IOException e) {  
			e.printStackTrace();  
		} finally {  
			try {
				if(writer != null){
					writer.close();
				}
				if(os != null){
					os.close();
				}
			} catch (Exception e2) {
				
			}
		}  
		return false;
	}
	
}
